// 仪表盘页面JavaScript
class DashboardApp {
    constructor() {
        this.baseURL = '';
        this.refreshInterval = null;
        this.init();
    }

    init() {
        this.updateCurrentTime();
        this.loadDashboardData();
        this.startAutoRefresh();
        
        // 更新时间
        setInterval(() => this.updateCurrentTime(), 1000);
    }

    updateCurrentTime() {
        const now = new Date();
        const timeString = now.toLocaleString('zh-CN');
        const timeElement = document.getElementById('currentTime');
        if (timeElement) {
            timeElement.textContent = timeString;
        }
    }

    startAutoRefresh() {
        // 每分钟自动刷新数据
        this.refreshInterval = setInterval(() => {
            this.loadDashboardData();
        }, 60000);
    }

    stopAutoRefresh() {
        if (this.refreshInterval) {
            clearInterval(this.refreshInterval);
            this.refreshInterval = null;
        }
    }

    // API调用函数
    async apiCall(endpoint, options = {}) {
        try {
            const response = await fetch(`${this.baseURL}${endpoint}`, {
                headers: { 'Content-Type': 'application/json', ...options.headers },
                ...options
            });
            
            const data = await response.json();
            if (!response.ok) throw new Error(data.message || `HTTP错误! 状态: ${response.status}`);
            return data;
        } catch (error) {
            console.error('API调用失败:', error);
            this.showToast(`请求失败: ${error.message}`, 'error');
            throw error;
        }
    }

    // 加载仪表盘数据
    async loadDashboardData() {
        try {
            const [productsRes, workOrdersRes, productionRecordsRes] = await Promise.all([
                this.apiCall('/api/products'),
                this.apiCall('/api/workorders'),
                this.apiCall('/api/production-records')
            ]);

            const products = productsRes.data || [];
            const workOrders = workOrdersRes.data || [];
            const productionRecords = productionRecordsRes.data || [];

            this.updateStatistics(products, workOrders, productionRecords);
            this.updateWorkOrderChart(workOrders);
            this.loadRecentActivities();

        } catch (error) {
            console.error('加载仪表盘数据失败:', error);
            this.showToast('加载数据失败，请检查网络连接', 'error');
        }
    }

    // 更新统计数据
    updateStatistics(products, workOrders, productionRecords) {
        // 产品统计
        document.getElementById('totalProducts').textContent = products.length;
        const categories = [...new Set(products.map(p => p.category).filter(c => c))];
        document.getElementById('productCategories').textContent = categories.length;

        // 工单统计
        document.getElementById('totalWorkOrders').textContent = workOrders.length;
        const inProgressOrders = workOrders.filter(order => order.status === 'IN_PROGRESS');
        document.getElementById('inProgressOrders').textContent = inProgressOrders.length;

        // 生产记录统计
        document.getElementById('totalProductionRecords').textContent = productionRecords.length;
        
        // 今日记录统计
        const today = new Date().toDateString();
        const todayRecords = productionRecords.filter(record => {
            const recordDate = new Date(record.createTime).toDateString();
            return recordDate === today;
        });
        document.getElementById('todayRecords').textContent = todayRecords.length;

        // 计算完成率
        this.calculateCompletionRate(workOrders);
    }

    // 计算完成率
    calculateCompletionRate(workOrders) {
        const completedOrders = workOrders.filter(order => order.status === 'COMPLETED');
        const completionRate = workOrders.length > 0 ? 
            Math.round((completedOrders.length / workOrders.length) * 100) : 0;
        
        document.getElementById('completionRate').textContent = `${completionRate}%`;
    }

    // 更新工单状态图表
    updateWorkOrderChart(workOrders) {
        const statusCounts = {
            'PENDING': 0,
            'IN_PROGRESS': 0,
            'COMPLETED': 0,
            'CANCELLED': 0
        };

        workOrders.forEach(order => {
            if (statusCounts.hasOwnProperty(order.status)) {
                statusCounts[order.status]++;
            }
        });

        const chartContainer = document.getElementById('workOrderChart');
        chartContainer.innerHTML = `
            <div class="chart-data">
                <div class="chart-item pending">
                    <span class="chart-label">待处理</span>
                    <span class="chart-value">${statusCounts.PENDING}</span>
                </div>
                <div class="chart-item in-progress">
                    <span class="chart-label">进行中</span>
                    <span class="chart-value">${statusCounts.IN_PROGRESS}</span>
                </div>
                <div class="chart-item completed">
                    <span class="chart-label">已完成</span>
                    <span class="chart-value">${statusCounts.COMPLETED}</span>
                </div>
                <div class="chart-item cancelled">
                    <span class="chart-label">已取消</span>
                    <span class="chart-value">${statusCounts.CANCELLED}</span>
                </div>
            </div>
        `;
    }

    // 加载最近活动
    async loadRecentActivities() {
        try {
            const response = await this.apiCall('/api/production-records');
            const records = response.data || [];
            const recentRecords = records
                .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
                .slice(0, 10);

            this.renderRecentActivities(recentRecords);
        } catch (error) {
            console.error('加载最近活动失败:', error);
            document.getElementById('recentActivities').innerHTML = 
                '<div class="error">加载活动记录失败</div>';
        }
    }

    // 渲染最近活动
    renderRecentActivities(activities) {
        const container = document.getElementById('recentActivities');
        
        if (activities.length === 0) {
            container.innerHTML = '<div class="no-data">暂无活动记录</div>';
            return;
        }

        const activitiesHTML = activities.map(record => {
            const iconClass = this.getRecordTypeIconClass(record.recordType);
            const actionText = this.getRecordTypeText(record.recordType);
            const timeAgo = this.getTimeAgo(record.createTime);
            
            return `
                <div class="activity-item">
                    <div class="activity-icon ${iconClass}">
                        <i class="${this.getRecordTypeIcon(record.recordType)}"></i>
                    </div>
                    <div class="activity-content">
                        <h4>${actionText} - 数量: ${record.quantity}</h4>
                        <p>工作站: ${record.workstation} | 操作员: ${record.operator}</p>
                        <small class="activity-time">${timeAgo}</small>
                    </div>
                </div>
            `;
        }).join('');

        container.innerHTML = activitiesHTML;
    }

    // 获取记录类型图标类名
    getRecordTypeIconClass(recordType) {
        switch (recordType) {
            case 'PRODUCTION': return 'success';
            case 'REJECTION': return 'warning';
            case 'REWORK': return 'info';
            default: return 'secondary';
        }
    }

    // 获取记录类型图标
    getRecordTypeIcon(recordType) {
        switch (recordType) {
            case 'PRODUCTION': return 'fas fa-check';
            case 'REJECTION': return 'fas fa-exclamation-triangle';
            case 'REWORK': return 'fas fa-redo';
            default: return 'fas fa-info';
        }
    }

    // 获取记录类型文本
    getRecordTypeText(recordType) {
        switch (recordType) {
            case 'PRODUCTION': return '完成生产';
            case 'REJECTION': return '记录不合格';
            case 'REWORK': return '返工处理';
            default: return '其他记录';
        }
    }

    // 计算时间差
    getTimeAgo(dateString) {
        const now = new Date();
        const past = new Date(dateString);
        const diffMs = now - past;
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMs / 3600000);
        const diffDays = Math.floor(diffMs / 86400000);

        if (diffMins < 1) return '刚刚';
        if (diffMins < 60) return `${diffMins}分钟前`;
        if (diffHours < 24) return `${diffHours}小时前`;
        if (diffDays < 7) return `${diffDays}天前`;
        return past.toLocaleDateString('zh-CN');
    }

    // 显示提示信息
    showToast(message, type = 'info') {
        const toast = document.getElementById('toast');
        toast.textContent = message;
        toast.className = `toast ${type}`;
        toast.classList.add('show');
        
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }

    // 生成报表
    generateReport() {
        this.showToast('报表生成功能开发中...', 'info');
        // TODO: 实现报表生成功能
    }
}

// 全局函数
function refreshDashboard() {
    if (window.dashboardApp) {
        window.dashboardApp.loadDashboardData();
        window.dashboardApp.showToast('数据已刷新', 'success');
    }
}

function loadRecentActivities() {
    if (window.dashboardApp) {
        window.dashboardApp.loadRecentActivities();
    }
}

function generateReport() {
    if (window.dashboardApp) {
        window.dashboardApp.generateReport();
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    window.dashboardApp = new DashboardApp();
});

// 页面卸载时清理定时器
window.addEventListener('beforeunload', function() {
    if (window.dashboardApp) {
        window.dashboardApp.stopAutoRefresh();
    }
});